package com.android.weibogo;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;

import com.android.weibogo.R;
import com.android.weibogo.WeibogoData.Accounts;
import com.android.weibogo.WeibogoData.WeiboAccounts;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class WeiboSelector extends Activity{
	private static final String TAG = "WeiboSelector";
	/**
	 * weibogo account id
	 */
	private String mWeibogoAccountId;
    /**
     * The content URI to the weibo account table
     */
	private Uri mUri;
	/**
	 * the weibogo user name
	 */
	private String mUserName;
    /**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
    	WeiboAccounts._ID, // 0
    	WeiboAccounts.WEIBOGO_ACCOUNT_ID, //1
    	WeiboAccounts.WEIBO_NAME, // 2
    	WeiboAccounts.TOKEN, //3
    	WeiboAccounts.TOKEN_SECRET, //4
    	WeiboAccounts.USER_NAME, //5
    	WeiboAccounts.USER_ICON, //6
    	WeiboAccounts.IS_DEFAULT_ACCOUNT
    };
    private static final String tecentWeiboName = "tecent";
    private static final String sinaWeiboName = "sina";
    
    @Override
    public void onCreate(Bundle savedInstanceState) { 
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.weiboselector);
        RelativeLayout layout = (RelativeLayout)findViewById(R.id.weibosel_layout);
        layout.setBackgroundResource(R.drawable.background);
        Intent intent = getIntent();
        Cursor cursor;
        mUri = intent.getData();
        mWeibogoAccountId = intent.getStringExtra("weibogoAccountId");
        if(mWeibogoAccountId != null){
	        //get the weibogo user name according to weibogoAccountId
    		String[] PROJECTION = new String[] {
        	    	Accounts.NAME // 0
        	    };
    		String selection = Accounts._ID + " =" + mWeibogoAccountId;
    		cursor = getContentResolver().query(Accounts.CONTENT_URI, PROJECTION, selection, null, WeibogoData.DEFAULT_SORT_ORDER);
    		if(cursor != null && cursor.getCount() > 0){
    			cursor.moveToFirst(); //assure only one record matches
    			int idx = cursor.getColumnIndex(Accounts.NAME);
    			mUserName = cursor.getString(idx);
    			cursor.close();
    		}else{
    			Log.e(TAG, "invalid account id, no corresponding record to this account id");
    			finish();
    		}
        }else{
    		//find if exists default user in the weibogo account table
    		String[] PROJECTION = new String[] {
    	    	Accounts._ID,  // 0
    	    	Accounts.NAME // 1
    	    };
    		String selection = Accounts.IS_DEFAULT_USER + " ='" + WeibogoData.YES + "'";
    		cursor = getContentResolver().query(Accounts.CONTENT_URI, PROJECTION, selection, null, WeibogoData.DEFAULT_SORT_ORDER);
    		if(cursor != null && cursor.getCount() > 0){
    			//get the default weibogo user
    			cursor.moveToFirst(); //assure only one record matches
    			int idx = cursor.getColumnIndex(Accounts._ID);
    			mWeibogoAccountId = cursor.getString(idx);
    			idx = cursor.getColumnIndex(Accounts.NAME);
    			mUserName = cursor.getString(idx);
    			cursor.close();
    		}else{
    			Log.e(TAG, "No default user, should chose default user firstly");
    			finish();
    		}
        }
        //setup views, view related initialization
        setupViews();
    }

	private void setupViews() {
		TextView userName = (TextView)findViewById(R.id.weibogo_username);
		userName.setText(mUserName);
		ImageButton backImgBtn = (ImageButton)findViewById(R.id.back);
		backImgBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//go back to the WeibogoAccounts activity
	        	Intent intent = new Intent(getApplication(), WeibogoAccounts.class);
	        	intent.setData(Accounts.CONTENT_URI);
	        	intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
	            startActivity(intent);
	            finish();
			}
		});
		ImageButton imgBtn = (ImageButton) findViewById(R.id.tecent_img_btn);
		imgBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String selection = WeiboAccounts.WEIBOGO_ACCOUNT_ID + " ="
						+ mWeibogoAccountId + " AND "
						+ WeiboAccounts.WEIBO_NAME + " = '" + tecentWeiboName
						+ "'";
				Cursor cursor = getContentResolver().query(mUri, PROJECTION,
						selection, null, WeibogoData.DEFAULT_SORT_ORDER);
				if (cursor == null || cursor.getCount() <= 0) {
					// new user account
					Intent intent = new Intent(getApplicationContext(),
							Authorization.class);
					intent.setData(mUri);
					Bundle extras = new Bundle();
					extras.putString("weibogoAccountId", mWeibogoAccountId);
					extras.putString("weiboName", tecentWeiboName);
					intent.putExtras(extras);
					startActivityForResult(intent, 0);
				} else {
					cursor.moveToFirst();
					int idx = cursor.getColumnIndex(WeiboAccounts.USER_NAME);
					String userName = cursor.getString(idx);
					idx = cursor.getColumnIndex(WeiboAccounts.TOKEN);
					String tokenKey = cursor.getString(idx);
					idx = cursor.getColumnIndex(WeiboAccounts.TOKEN_SECRET);
					String tokenSecret = cursor.getString(idx);
					idx = cursor.getColumnIndex(WeiboAccounts._ID);
					int id = cursor.getInt(idx);
					//remove the default weibo account flag 
					selection = WeiboAccounts.WEIBOGO_ACCOUNT_ID + " ="
						+ mWeibogoAccountId + " AND " + WeiboAccounts.IS_DEFAULT_ACCOUNT + " ='" + WeibogoData.YES + "'";
					ContentValues values = new ContentValues();
					values.put(WeiboAccounts.IS_DEFAULT_ACCOUNT, WeibogoData.NO);
					getContentResolver().update(mUri, values, selection, null);					
					//set the new default weibo account flag
					Uri tmpUri = ContentUris.withAppendedId(mUri, id);
					values.put(WeiboAccounts.IS_DEFAULT_ACCOUNT, WeibogoData.YES);
					getContentResolver().update(tmpUri, values, null, null);
					
					Intent intent = new Intent(getApplicationContext(),
							WeiboHome.class);
					Bundle extras = new Bundle();
					extras.putString("userName", userName);
					extras.putString("weiboName", tecentWeiboName);
					extras.putString("tokenKey", tokenKey);
					extras.putString("tokenSecret", tokenSecret);
					intent.putExtras(extras);
					intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
					startActivity(intent);
				}
				//close the cursor
				cursor.close();
			}
		});
	}
}
